

// plugins/my-plugin/assets/javascripts/discourse/components/share-link-component.js.es6

import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { ajax } from "discourse/lib/ajax";

export default Component.extend({
    router: service(),

    init() {
        this._super(...arguments);

    },

    actions: {
        async syncToGitee() {
            try {
                this.set('isSyncing', true);


                const token = settings.gitee_token

                const currentPath = this.router.currentURL;
        //     // 使用正则提取
                const topicIdMatch = currentPath.match(/\/t\/[^\/]+\/(\d+)/) || currentPath.match(/\/t\/(\d+)/);
                const topicId = topicIdMatch ? topicIdMatch[1] : null;
                const data = await ajax(`/t/${topicId}.json`);
                const title = data.title;
                var content = data.post_stream.posts[0].cooked;

                // content最后在增加一行，注明来源链接，如问题来源
                content = content + `\n\n---\n\n_问题来自 openKylin 论坛：[${title}](${window.location.origin + currentPath})_`;

                if (!confirm(`是否将帖子《${title}》同步到 Gitee？`)) {
                    return
                }

                const owner = settings.repo_owner;
                const repo = settings.repo_name;

                const res = await fetch(`https://gitee.com/api/v5/repos/${owner}/issues`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `token ${token}`
                    },
                    body: JSON.stringify({
                        access_token: token,
                        title: (settings.issue_template_prefix || '') + title,
                        body: content,
                        owner: owner,
                        repo: repo
                    })
                });


                if (!res.ok) {
                    const err = await res.text();
                    throw new Error(err);
                }


                const json = await res.json();
                alert(`同步成功！已创建 Issue: ${json.html_url}`);


            } catch (e) {
                alert(`同步失败: ${e.message}`);
                console.error(e);
            } finally {
                this.set('isSyncing', false);
            }
        }
    }
});